const express = require('express');
const router = express.Router();
const mysql = require('mysql2/promise');

const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: '123456', // 请根据实际情况修改
    database: 'gamebag',
    multipleStatements: true
};
async function getConn() {
    return await mysql.createConnection(dbConfig);
}

// 物品使用接口
// POST /api/characters/:id/use-item
router.post('/api/characters/:id/use-item', async (req, res) => {
    const { itemId, qty } = req.body;
    const characterId = req.params.id;
    const useQty = Math.max(1, parseInt(qty) || 1);
    const conn = await getConn();
    // 检查背包
    const [bagRows] = await conn.execute('SELECT * FROM bags WHERE character_id=? AND item_id=?', [characterId, itemId]);
    if (!bagRows.length || bagRows[0].qty < useQty) {
        await conn.end();
        return res.status(400).json({ error: '背包中无足够该物品' });
    }
    // 获取物品信息
    const [itemRows] = await conn.execute('SELECT * FROM items WHERE id=?', [itemId]);
    if (!itemRows.length) {
        await conn.end();
        return res.status(404).json({ error: '物品不存在' });
    }
    const item = itemRows[0];
    // 获取角色
    const [charRows] = await conn.execute('SELECT * FROM characters WHERE id=?', [characterId]);
    if (!charRows.length) {
        await conn.end();
        return res.status(404).json({ error: '角色不存在' });
    }
    let character = charRows[0];
    let updateFields = {};
    let effectMsg = '';
    // 计算最大生命和法力（基础+等级成长+装备+被动）
    // 基础：hp, mp 字段，等级成长：每级+20hp/+10mp，装备加成、被动加成见装备/技能
    // 取装备加成
    const [equipRows] = await conn.execute('SELECT i.hp_bonus FROM character_equipments ce LEFT JOIN items i ON ce.item_id = i.id WHERE ce.character_id=?', [characterId]);
    let equipHp = 0;
    for (const row of equipRows) { if (row && row.hp_bonus) equipHp += row.hp_bonus; }
    // 取被动技能加成
    const [passiveSkills] = await conn.execute('SELECT s.effect FROM character_skills cs JOIN skills s ON cs.skill_id = s.id WHERE cs.character_id=? AND s.type="被动"', [characterId]);
    let skillHp = 0, skillMp = 0;
    for (const row of passiveSkills) {
        if (!row || !row.effect) continue;
        let effect = {};
        try { effect = JSON.parse(row.effect); } catch { }
        if (effect.hp_up) skillHp += effect.hp_up;
        if (effect.mp_up) skillMp += effect.mp_up;
    }
    // 最大生命/法力
    const maxHp = (100 + (character.level - 1) * 20) + equipHp + skillHp;
    const maxMp = (50 + (character.level - 1) * 10) + skillMp; // 假设装备无mp加成
    // 物品使用逻辑
    if (item.type === '消耗品') {
        if (item.name.includes('生命') || item.desc.includes('生命')) {
            // 恢复HP
            let heal = 0;
            if (/\d+/.test(item.desc)) heal = parseInt(item.desc.match(/\d+/)[0]);
            heal = heal * useQty;
            let newHp = Math.min(character.hp + heal, maxHp);
            await conn.execute('UPDATE characters SET hp=? WHERE id=?', [newHp, characterId]);
            effectMsg = `恢复生命${newHp - character.hp}`;
        } else if (item.name.includes('法力') || item.desc.includes('法力')) {
            // 恢复MP
            let heal = 0;
            if (/\d+/.test(item.desc)) heal = parseInt(item.desc.match(/\d+/)[0]);
            heal = heal * useQty;
            let newMp = Math.min(character.mp + heal, maxMp);
            await conn.execute('UPDATE characters SET mp=? WHERE id=?', [newMp, characterId]);
            effectMsg = `恢复法力${newMp - character.mp}`;
        } else {
            effectMsg = '使用了消耗品';
        }
    } else if (item.type === '道具') {
        // 例如魔法卷轴可触发技能（可扩展）
        if (item.name.includes('火球')) {
            // 触发火球术
            effectMsg = '释放火球术！';
        } else {
            effectMsg = '使用了道具';
        }
    } else {
        await conn.end();
        return res.status(400).json({ error: '该物品不可直接使用' });
    }
    // 扣除背包数量
    if (bagRows[0].qty === useQty) {
        await conn.execute('DELETE FROM bags WHERE id=?', [bagRows[0].id]);
    } else {
        await conn.execute('UPDATE bags SET qty=qty-? WHERE id=?', [useQty, bagRows[0].id]);
    }
    // 返回最新角色属性和背包
    const [charRows2] = await conn.execute('SELECT * FROM characters WHERE id=?', [characterId]);
    const [bag] = await conn.execute('SELECT b.id as bag_id, i.id as item_id, i.name, i.desc, i.type, i.rarity, b.qty FROM bags b JOIN items i ON b.item_id = i.id WHERE b.character_id = ?', [characterId]);
    await conn.end();
    res.json({ success: true, effectMsg, character: charRows2[0], bag });
});

module.exports = router; 